package com.fastfly.domain;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;

public class CreditCard implements Serializable {
	
	protected final Log log = LogFactory.getLog(getClass());

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	protected String cardNumber, cardHolderName, expMonth, expYear, address;
	
	public final static String[] MONTHS = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
	public final static String[] YEARS = {"2009", "2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017"};

	public String getCardNumber() {
		return cardNumber;
	}

	public void setCardNumber(String cardNumber) {
		this.cardNumber = cardNumber;
	}

	public String getCardHolderName() {
		return cardHolderName;
	}

	public void setCardHolderName(String cardHolderName) {
		this.cardHolderName = cardHolderName;
	}

	public String getExpMonth() {
		return expMonth;
	}

	public void setExpMonth(String expMonth) {
		this.expMonth = expMonth;
	}

	public String getExpYear() {
		return expYear;
	}

	public void setExpYear(String expYear) {
		this.expYear = expYear;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String[] getMonths() {
		return MONTHS;
	}

	public String[] getYears() {
		return YEARS;
	}
	
	public void validatePayWithCreditCard(ValidationContext context) {
		MessageContext messages = context.getMessageContext();
		SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
		sdf.setLenient(false);
		
		try {			
			String strDate = "02 " + getExpMonth() + " " + getExpYear();
			log.debug("strDate: " + strDate);
			Date date = sdf.parse(strDate);
			
			Calendar cal = Calendar.getInstance();
			cal.set(Calendar.DAY_OF_MONTH, 1);		
			
			log.debug("cal.getTime(): " + cal.getTime() + " - date: " + date);
			if (  date.before( cal.getTime() ) ) {			
				messages.addMessage(new MessageBuilder().error().defaultText("Credit Card has expired!").build());
			}
			
		} catch (ParseException e) {
			log.error(e, e);
			messages.addMessage(new MessageBuilder().error().defaultText("Invalid Date!").build());
			
			
		} 
	}

	
	

}
